package so.shanku.essential.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.bean.SocializeConfig;
import com.umeng.socialize.sso.UMSsoHandler;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.HotGoodsAdapter;
import so.shanku.essential.adapter.RelationProductAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.ImageLoaderBitmapCallBack;
import so.shanku.essential.utils.Utils;
import so.shanku.essential.view.GridViewNoScroll;
import so.shanku.essential.view.ScalRefreshScrollView;
import striveen.util.used.view.view.gridview.PLA_AdapterView;

import java.util.*;

/**
 * Created by Jaelyn on 2015/9/16 0016.
 * 店铺首页
 */
public class ShopActivity extends BaseUIActivity {
    /**
     * 刷新的
     */
    @ViewInject(id = R.id.ptr_scrollview)
    private ScalRefreshScrollView ptr_scrollview;
    @ViewInject(id = R.id.xgv)
    private GridViewNoScroll xgv;
    @ViewInject(id = R.id.content_info_layout)
    private LinearLayout content_info_layout;

    /**
     * head view
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_bg_iv)
    private ImageView shop_bg_iv;//商品图片
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_name_logo)
    private ImageView shop_name_logo;//店铺的名字的logo
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_discri)
    private TextView shop_discri;//商品描述
    //	@com.lidroid.xutils.view.annotation.ViewInject(R.id.detail_more)
//	private TextView detail_more;//详情
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.attention_tag_iv)
    private TextView attention_tag_iv;//添加关注

    /**
     * 热门商品的布局
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.hot_goods_layout)
    private LinearLayout hot_goods_layout;

    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_hot_goods_vp)
    private ViewPager shop_hot_goods_vp; //商品的图片
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.view_ind_layout)
    private LinearLayout view_ind_layout;     //指示器
    /**
     * 定时器
     */
    private Timer timer;
    private FulstTimerTask timerTask;
    /**
     * 男士女士（当其中一个数据为空，不显示男士女士，直接展示）
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_man_or_woman)
    private LinearLayout shop_man_or_woman;
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.manType_tv)
    private TextView manType_tv;//男士
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.womanType_tv)
    private TextView womanType_tv;//女士
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.all_product) //所有商品
    private TextView all_product;

    private List<JsonMap<String, Object>> dataList = new ArrayList<JsonMap<String, Object>>();
    private List<JsonMap<String, Object>> womanDatas = new ArrayList<JsonMap<String, Object>>();
    private int manCurrentPage = 0;
    private int womanCurrentPage = 0;
    private boolean manCanLoadMore = true;
    private boolean womanCanLoadMore = true;
    private String shopId = ""; //店铺的id
    private String shopName = "";//店铺名字

    private int typeId = 1;//男女类型 1：男士 2：女士
    /**
     * 下拉刷新Gridview适配器
     */
    private RelationProductAdapter relationProductAdapter;

    /**
     * 商品图片展示图
     */
    private HotGoodsAdapter hotGoodsAdapter;
    private List<JsonMap<String, Object>> hotGoodsDatas;
    private JsonMap shopDatas; //店铺信息

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shoplayout);
        setBtn_menuText(R.string.share, shareMenuListener);
        shopId = getIntent().getStringExtra(Constant.ID);
        ptr_scrollview.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        setCenter_title(shopName);
        addHeadView();
        getServerData();
    }

    /**
     * 拉取店铺信息
     */
    private void getServerData() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();

        if (Utils.isHasLogin(this)) {
            params.put("userId", Utils.getUserId(this));
        }
        params.put("shopId", shopId);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.GetAction_GetVendorDetails);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetVendorDetails);
        getDataUtil.getData(queue);
    }


    private void setSelection(int typeId) {
        this.typeId = typeId;
        if (typeId == 1) {
            manType_tv.setSelected(true);
            womanType_tv.setSelected(false);
        } else {
            manType_tv.setSelected(false);
            womanType_tv.setSelected(true);
        }
    }


    /**
     * 选择男士
     *
     * @param view
     */
    @OnClick(R.id.manType_tv)
    public void manType_tv_click(View view) {
        if (this.typeId == 1) {
            return;
        }
        setSelection(1);
        if (dataList == null || dataList.size() == 0) {
            manCurrentPage = 0;
            getRelationGoods();
        } else {
            setAdatper_data();
        }
    }

    /**
     * 选择女士
     *
     * @param view
     */
    @OnClick(R.id.womanType_tv)
    public void womanType_tv_click(View view) {
        if (this.typeId == 2) {
            return;
        }
        setSelection(2);
        if (womanDatas == null || womanDatas.size() == 0) {
            womanCurrentPage = 0;
            getRelationGoods();
        } else {
            setAdatper_data();
        }
    }


    /**
     * 详情显示
     *
     * @param view
     */
    @OnClick(R.id.detail_more)
    public void detail_more_click(View view) {
        Intent intent = new Intent(mContext, ShopIntroductionActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, shopDatas.getStringNoNull("shopId"));
        jumpTo(intent);
    }

    /**
     * 关注按钮点击
     *
     * @param view
     */
    @OnClick(R.id.attention_tag_iv)
    public void attention_tag_iv_click(View view) {
        getDate_GetFocusOn(callBack, shopId, this);
    }

    //顶部切换时调用 刷新listview数据
    private void setAdatper_data() {
        if (typeId == 1) {
            relationProductAdapter.setDatas(dataList);
        } else {
            relationProductAdapter.setDatas(womanDatas);
        }
        relationProductAdapter.notifyDataSetChanged();

    }

    /**
     * 添加头部
     */
    private void addHeadView() {
        View headView = getLayoutInflater().inflate(R.layout.shop_head_layout, null);
        ViewUtils.inject(this, headView);
        content_info_layout.addView(headView, 0);
        ptr_scrollview.setOnRefreshListener(loadMoreListener);
        relationProductAdapter = new RelationProductAdapter(this);
        relationProductAdapter.setDatas(dataList);
        xgv.setAdapter(relationProductAdapter);
        xgv.setOnItemClickListener(onItemClickListener);
        ptr_scrollview.setImageView(shop_bg_iv);
    }

    /**
     * 刷洗监听
     */
    private PullToRefreshBase.OnRefreshListener2 loadMoreListener = new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
            ptr_scrollview.onRefreshComplete();
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
            getRelationGoods();
        }
    };

    /**
     * item的点击
     */
    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (typeId == 1) {
                JsonMap jsonmap = dataList.get(position);
                String goodsId = jsonmap.getStringNoNull("ProductId");
                seeProductDetail(goodsId);
            } else {
                JsonMap jsonmap = womanDatas.get(position);
                String goodsId = jsonmap.getStringNoNull("ProductId");
                seeProductDetail(goodsId);
            }
        }
    };


    /**
     * 获取商品  {shopId:165,typeId:2,nPage:1}
     */
    private void getRelationGoods() {
        //xgv.setBoolInterceptTouchEvent(true);
        Map<String, Object> params = new HashMap<String, Object>();
        if (typeId == 1) {
            params.put("nPage", manCurrentPage + 1);
        } else {
            params.put("nPage", womanCurrentPage + 1);
        }
        params.put("shopId", shopId);
        params.put("typeId", typeId);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.GetAction_SelectVendorProductList);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_SelectVendorProductList);
        getDataUtil.getData(queue);
    }


    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_SelectVendorProductList) {
                        ptr_scrollview.onRefreshComplete();
                        List<JsonMap<String, Object>> data_server = JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        setData(data_server);
                        validateData(data_server);
                    } else if (entity.what == GetDataConfing.What_GetVendorDetails) {
                        try {
                            shopDatas = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                            refreshShopDetail();
                        } catch (Exception e) {
                            e.printStackTrace();
                            toast.showToast(R.string.server_error);
                            finish();
                        }

                    } else if (entity.what == GetDataConfing.WHAT_GET_FOCUS_ON) { //关注平拍
                        JsonMap<String, Object> data = JsonParseHelper
                                .getJsonMap(entity.getInfo());
                        try {
                            String msg = data.getString(JsonKeys.Key_Msg);
                            JsonMap temp = data.getList_JsonMap(JsonKeys.Key_Info).get(0);
                            String vendorId = temp.getStringNoNull("VendorId");
                            //toast.showToast(msg);

                            if (temp.getBoolean("IsFocus")) {
                                changeAttendStatue(true);
                                updateAttentionStatues(vendorId, true);
                            } else {
                                //removeFavourtePrograme(programId);
                                //jiemu_collect.setImageResource(R.drawable.icon_collect_no);
                                updateAttentionStatues(vendorId, false);
                                changeAttendStatue(false);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    if (entity.what == GetDataConfing.What_SelectVendorPostList) {
                        ptr_scrollview.onRefreshComplete();
                    }
                }
            } else {
                if (entity.what == GetDataConfing.What_SelectVendorPostList) {
                    ptr_scrollview.onRefreshComplete();
                }
                ShowGetDataError.showNetError(mContext);
            }
            loadingToast.dismiss();
        }

    };

    /**
     * 设置商品信息 并请求相关商品的信息
     */
    private void refreshShopDetail() {
        shopName = shopDatas.getStringNoNull("shopName");
        setCenter_title(shopName);
        String backImge = shopDatas.getStringNoNull("backGroundImage");   //背景大图
        if (MyApplication.getInstance().getBitmapHashMap().containsKey(backImge)) {
            shop_bg_iv.setImageBitmap(MyApplication.getInstance().getBitmapHashMap().get(backImge));
        } else {
            ImageLoader.getInstance().displayImage(backImge, shop_bg_iv, MyApplication.getInstance().getShopBgOption(), new ImageLoaderBitmapCallBack());
        }

        String shopLogo = shopDatas.getStringNoNull("shopLogo"); //店铺logo
        ImageLoader.getInstance().displayImage(shopLogo, shop_name_logo, new ImageLoaderBitmapCallBack());


        boolean isFocus = shopDatas.getBoolean("isCollected");

        changeAttendStatue(isFocus);


        hotGoodsDatas = shopDatas.getList_JsonMap("hotProducts");
        if (hotGoodsDatas.isEmpty()) {
            hot_goods_layout.setVisibility(View.GONE);
        } else {
            hot_goods_layout.setVisibility(View.VISIBLE);
            hotGoodsAdapter = new HotGoodsAdapter(this, hotGoodsDatas);
            hotGoodsAdapter.setOnItemClickListener(new HotGoodsAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int index) {
                    String goodsId = hotGoodsDatas.get(index).getStringNoNull("productId");
                    seeProductDetail(goodsId);
                }
            });
            hotGoodsAdapter.setIndContainerView(view_ind_layout);
            shop_hot_goods_vp.addOnPageChangeListener(hotGoodsAdapter);
            shop_hot_goods_vp.setAdapter(hotGoodsAdapter);
            shop_hot_goods_vp.setCurrentItem(0);
//			if (hotGoodsDatas.size() > 1) {
//				//timer.schedule(timerTask, 3000, 3000);
//				shop_hot_goods_vp.setOnTouchListener(new View.OnTouchListener() {
//
//					@Override
//					public boolean onTouch(View v, MotionEvent event) {
//						if (event.getAction() == MotionEvent.ACTION_DOWN) {
//							isDown = true;
//						} else if (event.getAction() == MotionEvent.ACTION_UP) {
//							time = System.currentTimeMillis();
//							isDown = false;
//						}
//						return false;
//					}
//				});
//			}
        }

        shop_discri.setText(shopDatas.getStringNoNull("shopDiscri"));
        String mrCount = shopDatas.getStringNoNull("mrCount");
        String msCount = shopDatas.getStringNoNull("msCount");
        String mrTitle = String.format(getString(R.string.shop_man), mrCount);
        String msTitle = String.format(getString(R.string.shop_woman), msCount);

        manType_tv.setText(mrTitle);
        womanType_tv.setText(msTitle);
        if (TextUtils.isEmpty(mrCount) || TextUtils.isEmpty(msCount)) {
            shop_man_or_woman.setVisibility(View.GONE);
            if (!mrCount.equals("0")) {
                typeId = 1;
                getRelationGoods();
                String allTitle = String.format(getString(R.string.all_product), mrCount);
                all_product.setText(allTitle);
                all_product.setVisibility(View.VISIBLE);
            } else if (!msCount.equals("0")) {
                String allTitle = String.format(getString(R.string.all_product), msCount);
                all_product.setText(allTitle);
                all_product.setVisibility(View.VISIBLE);
                typeId = 2;
                getRelationGoods();
            } else {
                all_product.setVisibility(View.GONE);
            }
        } else {
            all_product.setVisibility(View.GONE);
            shop_man_or_woman.setVisibility(View.VISIBLE);
            setSelection(1);
            getRelationGoods();
        }
    }

    /**
     * 定时刷新倒计时
     */
    private class FulstTimerTask extends TimerTask {

        @Override
        public void run() {
            handler.sendEmptyMessage(0);
        }

    }

    /**
     * 是否有手指点击在广告上
     */
    private boolean isDown = false;
    private long time;
    private boolean isFulshGuangGao = true;
    /**
     * 定时刷新倒计时执行者
     */
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            // fulsuQiangGouShiJian();
            /*
             * 隔两秒刷新广告
			 */
            isFulshGuangGao = (!isFulshGuangGao);
            if (isFulshGuangGao && !isDown
                    && System.currentTimeMillis() - time > 1000) {
                if (shop_hot_goods_vp == null || shop_hot_goods_vp.getChildCount() == 0) {
                    return;
                }
                int defSelect = shop_hot_goods_vp.getCurrentItem();

                defSelect++;
                defSelect = defSelect % shop_hot_goods_vp.getChildCount();
                shop_hot_goods_vp.setCurrentItem(defSelect, true);

            }

        }

        ;
    };

    /**
     * 更改关注状态
     *
     * @param isFocus
     */
    private void changeAttendStatue(boolean isFocus) {
        attention_tag_iv.setSelected(isFocus);
        if (isFocus) {
            attention_tag_iv.setText(R.string.attentioned);
        } else {
            attention_tag_iv.setText(R.string.attention);
        }
    }

    private void setData(List<JsonMap<String, Object>> data_server) {
        if (typeId == 1) {

            if (manCurrentPage == 0) {
                dataList = data_server;
                relationProductAdapter.setDatas(data_server);
                xgv.setAdapter(relationProductAdapter);
                relationProductAdapter.notifyDataSetChanged();
            } else {
                dataList.addAll(data_server);
                relationProductAdapter.notifyDataSetChanged();
            }
            manCurrentPage++;
        } else {

            if (womanCurrentPage == 0) {
                womanDatas = data_server;
                relationProductAdapter.setDatas(data_server);
                xgv.setAdapter(relationProductAdapter);
                relationProductAdapter.notifyDataSetChanged();
            } else {
                womanDatas.addAll(data_server);
                relationProductAdapter.notifyDataSetChanged();
            }
            womanCurrentPage++;
        }
    }


    /**
     * 校验数据 显示无数据等
     *
     * @param data_server
     */
    private void validateData(List<JsonMap<String, Object>> data_server) {
        if (typeId == 1) {
            if (data_server.size() == 0) {
                ptr_scrollview.setMode(PullToRefreshBase.Mode.DISABLED);
                manCanLoadMore = false;
            }
        } else {
            if (data_server.size() == 0) {
                ptr_scrollview.setMode(PullToRefreshBase.Mode.DISABLED);
                womanCanLoadMore = false;
            }
        }
    }


    private View.OnClickListener shareMenuListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String shareLogo = shopDatas.getStringNoNull("brandLogo");
            String shareTitle = shopDatas.getStringNoNull("ShopName");
            String shareContent = shopDatas.getStringNoNull("VendorInfo");
            String shareUrl = "ShopMall/Index?vid=" + shopId;

            MyApplication.getInstance().showShareCompont(mContext, shareLogo, shareUrl, shareTitle, shareContent);
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */

//		UMSocialService umSocialService=MyApplication.getInstance().getmController();
//		if(umSocialService!=null) {
//			UMSsoHandler ssoHandler =umSocialService.getConfig().getSsoHandler(requestCode);
//			if (ssoHandler != null) {
//				ssoHandler.authorizeCallBack(requestCode, resultCode, data);
//			}
//		}
        UMSsoHandler ssoHandler = SocializeConfig.getSocializeConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    private void stopTimer() {
        if (timer != null) {
//			try {
//				timerTask.cancel();
//				timer.cancel();
//				timerTask = null;
//				timer = null;
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
        }
    }
}